package com.dpad.telematicsclientapp.presenter

import android.util.Log

import com.dpad.crmclientapp.android.util.utils.*
import com.dpad.telematicsclientapp.loginmodule.KtLoginActivity
import com.dpad.telematicsclientapp.mvp.event.BusProvider
import com.dpad.telematicsclientapp.mvp.kit.Kits
import com.dpad.telematicsclientapp.mvp.mvp.XPresent
import com.dpad.telematicsclientapp.netlibrary.MainApplicaton
import com.dpad.telematicsclientapp.netlibrary.http.NetInstance
import com.dpad.telematicsclientapp.netlibrary.http.NetworkUtil
import com.dpad.telematicsclientapp.netlibrary.newapp.entity.*
import com.dpad.telematicsclientapp.util.DataStatisticsUtils
import com.dpad.telematicsclientapp.util.MD5
import com.dpad.telematicsclientapp.util.PreferenceUtils
import com.dpad.telematicsclientapp.util.TitleToCode
import com.dpad.telematicsclientapp.util.utils.*
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import java.util.*

/**
 * ================================================
 * 作    者：wenbody
 * 版    本：1.0
 * 创建日期：2019/12/17 15:42
 * 描    述：
 * 修订历史：
 * ================================================
 */
class LoginPresenter : XPresent<KtLoginActivity>() {
    fun startLogin(userName: String, pwd: String, loginByPsw: Boolean) {
        val sortedMap: SortedMap<String, Any> = TreeMap()
        sortedMap["userName"] = userName
        if (loginByPsw) {
            sortedMap["userPwd"] = MD5.GetMD5Code(pwd)
            DataStatisticsUtils.addData(DataStatisticsUtils.getDatasBean("", TitleToCode.TYPE164.title, System.currentTimeMillis().toString() + "", Constant.NOMAL))
        } else {
            sortedMap["poneCode"] = pwd
            DataStatisticsUtils.addData(DataStatisticsUtils.getDatasBean("", TitleToCode.TYPE165.title, System.currentTimeMillis().toString() + "", Constant.NOMAL))
        }
        v.loading("正在登录...")
        PreferenceUtils.getInstance(v.mContext()).setString("USERNAME", "")
        PreferenceUtils.getInstance(v.mContext()).setString("TOKEN", "")
        PreferenceUtils.getInstance(v.mContext()).setString("isAgree", "")
        PreferenceUtils.getInstance(v.mContext()).setString("city", "")
        PreferenceUtils.getInstance(v.mContext()).setString("citycode", "")
        MainApplicaton.LOGINRESULTVO.token = ""
        MainApplicaton.LOGINRESULTVO.userName = ""
        MainApplicaton.LOGINRESULTVO.isAgree = ""
        MainApplicaton.city = ""
        MainApplicaton.citycode = ""
        MainApplicaton.sIsLogin = false
        MainApplicaton.userVehType = "0"
        MainApplicaton.setBurialPointUserType("1")
        NetInstance.getEventsService()
                .login(ParameterUtils.getHeaser(sortedMap), ParameterUtils.getJsonBody(sortedMap))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Observer<LoginBean> {
                    override fun onSubscribe(d: Disposable) {
                        addDisposable(d)
                    }

                    override fun onNext(loginBean: LoginBean) {
                        if (loginBean.code == "00000") {
                            /**
                             * 登录成功
                             */



                            MainApplicaton.LOGINRESULTVO.token = loginBean.result.token
                            MainApplicaton.LOGINRESULTVO.userName = loginBean.result.userName
                            MainApplicaton.LOGINRESULTVO.userId = loginBean.result.userId
                            MainApplicaton.LOGINRESULTVO.isAgree = loginBean.result.isAgree
                            MainApplicaton.LOGINRESULTVO.nickName = loginBean.result.nickName
                            /**
                             * 注册clientId
                             */
                            if (!Kits.Empty.check(MainApplicaton.clientId)) {
                                RegisterClientIdUtils.bindingClient(MainApplicaton.clientId)
                            }
                            PreferenceUtils.getInstance(v.mContext()).setString("USERNAME", loginBean.result.userName)
                            PreferenceUtils.getInstance(v.mContext()).setString(Constant.USERID_KEY, loginBean.result.userId)
                            PreferenceUtils.getInstance(v.mContext()).setString(Constant.LOGIN_NAME, loginBean.result.userName)
                            PreferenceUtils.getInstance(v.mContext()).setString(Constant.LOGIN_NICKNAME, loginBean.result.nickName)
                            PreferenceUtils.getInstance(v.mContext()).setString(Constant.LOGIN_USERPIC, loginBean.result.picUrl)
                            PreferenceUtils.getInstance(v.mContext()).setString("TOKEN", loginBean.result.token)
                            PreferenceUtils.getInstance(v.mContext()).setString("isAgree", loginBean.result.isAgree)
                            MainApplicaton.sIsLogin = true
                            MainApplicaton.setVin(if (Kits.Empty.check(loginBean.result.vin)) "" else loginBean.result.vin)
                            MainApplicaton.isTcar = !Kits.Empty.check(loginBean.result.isTServer) && loginBean.result.isTServer == "1"
                            MainApplicaton.setUserVehType(loginBean.result.userVehType)
                            MainApplicaton.setBurialPointUserType(loginBean.result.burialPointUserType)
                            MainApplicaton.setSaleSubmodelId(loginBean.result.saleSubmodeId)
//                            Log.e("AAAAA","帐号登录时的车型为"+loginBean.result.saleSubmodeId)
                            val userLoginStateChangeEvent = UserLoginStateChangeEvent(MainApplicaton.sIsLogin, MainApplicaton.isTcar)
                            BusProvider.getBus().post(userLoginStateChangeEvent)
                            //统计登录
//                            v.loginSuggess()
                            if (Kits.Empty.check(loginBean.result.saleSubmodeId)) {
                                v.dealLogin()
                            } else {
                                setPicUrl()
                            }
                        }

                    }

                    override fun onError(e: Throwable) {
                        v.loadingComplete()
                        v.dealHttpError(e)
                    }

                    override fun onComplete() {
                        v.loadingComplete()
                    }
                })
    }

    fun getTcarList() {
        v.loading("正在加载...")
        val sortedMap: SortedMap<String?, Any?> = TreeMap<String, Any?>()
        sortedMap["userId"] = MainApplicaton.LOGINRESULTVO.userId
        sortedMap["vin"] = MainApplicaton.vin
        NetInstance.getEventsService().tjihuo3(ParameterUtils.getHeaser(sortedMap), ParameterUtils.getJsonBody(sortedMap)).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(object : Observer<CardItem3> {
            override fun onSubscribe(d: Disposable) { //                        addDisposable(d);
            }

            override fun onNext(bean: CardItem3) {
                if (bean.code == "00000") {
                    v.showListViewData(bean.result)
                } else {
                }
            }

            override fun onError(e: Throwable) {
                v.loadingComplete();
                v.dealHttpError(e)
            }

            override fun onComplete() {
                v.loadingComplete();
            }
        })
    }



    fun aggreeTips() {
        v.loading("正在加载...")
        val sortedMap: SortedMap<String?, Any?> = TreeMap<String, Any?>()
        NetInstance.getEventsService().isagree(ParameterUtils.getHeaser(sortedMap), ParameterUtils.getJsonBody(sortedMap)).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(object : Observer<IsAgree> {
            override fun onSubscribe(d: Disposable) {
                addDisposable(d)
            }

            override fun onNext(bean: IsAgree) {
                if (bean.code == "00000") {
                    v.gotoTcar()
                }
            }

            override fun onError(e: Throwable) {
                v.loadingComplete()
                v.dealHttpError(e)
            }

            override fun onComplete() {
                v.loadingComplete()
            }
        })
    }


    fun selectjihuo() {
        v.loading("正在加载...")
        val sortedMap: SortedMap<String, Any> = TreeMap<String, Any>()
        sortedMap["userId"] = MainApplicaton.LOGINRESULTVO.userId
        sortedMap["vin"] = MainApplicaton.vin
        NetInstance.getEventsService()
                .tjihuo3(ParameterUtils.getHeaser(sortedMap), ParameterUtils.getJsonBody(sortedMap))
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Observer<CardItem3> {
                    override fun onSubscribe(d: Disposable) {
                        addDisposable(d)
                    }

                    override fun onNext(bean: CardItem3) {
                        if (bean.code == "00000") {
                            v.showListViewData(bean.result)
                        }
                    }

                    override fun onError(e: Throwable) {
                        v.loadingComplete()
                        v.dealHttpError(e)
                    }

                    override fun onComplete() {
                        v.loadingComplete()
                    }
                })
    }


    fun getVcoe(userName: String) {

        if (NetworkUtil.isNetworkAvailable(v.mContext())) {
            T.showToastSafeError("当前网络不可用,请检查网络设置!")
            v.getVcodeError()
            return
        }
        val sortedMap: SortedMap<String, Any> = TreeMap()
        sortedMap["phone"] = userName
        NetInstance.getEventsService()
                .getLoginCode(ParameterUtils.getHeaser(sortedMap), ParameterUtils.getJsonBody(sortedMap))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Observer<VcodeBean> {
                    override fun onSubscribe(d: Disposable) {
                        addDisposable(d)
                    }

                    override fun onNext(loginBean: VcodeBean) {
                        if (loginBean.code == "00000") {
                            T.showToastSafeOk("验证码获取成功")
                        } else {
                            v.getVcodeError()
                        }

                    }

                    override fun onError(e: Throwable) {
                        v.loadingComplete()
                        v.dealHttpError(e)
                        v.getVcodeError()
                    }

                    override fun onComplete() {
                        v.loadingComplete()
                    }
                })
    }

    //获取全局的图片地址
    fun setPicUrl() {
//        populevehicle 我的爱车车图
//        uservehicle 个人中心车图
//        ecovehicle 环保驾驶车图
//        indexvehicleinfo 首页车况报告车图
//        vehicleinfoblue 车况报告车图蓝底
//        vehicleinfored 车况报告车图红底
//        vehicleinfoyellow 车况报告车图黄底

        v.loading("正在加载...")
        val sortedMap: SortedMap<String?, Any?> = TreeMap<String?, Any?>()
        sortedMap["saleSubmodelId"] = MainApplicaton.getSaleSubmodelId()
        sortedMap["downloadType"] = "1" //0为zip 1为车型图片 2为远控图片
        NetInstance.getEventsService().picDownload(ParameterUtils.getHeaser(sortedMap), ParameterUtils.getJsonBody(sortedMap))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Observer<YckzZipEntity> {
                    override fun onSubscribe(d: Disposable) {
                        addDisposable(d)
                    }

                    override fun onNext(bean: YckzZipEntity) {
                        if (bean.code == "00000") {
                            MainApplicaton.urlMap.clear()
                            if (!bean.result.isNullOrEmpty()) {
                                for (item in bean.result) {
                                    if (!Kits.Empty.check(item.mark)) {
                                        when (item.mark) {
                                            "populevehicle" -> {
                                                MainApplicaton.urlMap["populevehicle"] = item.downloadPath
                                            }
                                            "uservehicle" -> {
                                                MainApplicaton.urlMap["uservehicle"] = item.downloadPath
                                            }
                                            "ecovehicle" -> {
                                                MainApplicaton.urlMap["ecovehicle"] = item.downloadPath
                                            }
                                            "indexvehicleinfo" -> {
                                                MainApplicaton.urlMap["indexvehicleinfo"] = item.downloadPath
                                            }
                                            "vehicleinfoblue" -> {
                                                MainApplicaton.urlMap["vehicleinfoblue"] = item.downloadPath
                                            }
                                            "vehicleinfored" -> {
                                                MainApplicaton.urlMap["vehicleinfored"] = item.downloadPath
                                            }
                                            "vehicleinfoyellow" -> {
                                                MainApplicaton.urlMap["vehicleinfoyellow"] = item.downloadPath
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        v.dealLogin()
                    }

                    override fun onError(e: Throwable) {
                        v.loadingComplete()
                        v.dealHttpError(e)
                        v.dealLogin()
                    }

                    override fun onComplete() {
                        v.loadingComplete()
                    }
                })
    }

}